#include "GL/glew.h"
#include "LoadShader.h"
#include "utility.h"
#include "vmath.h"
#include <iostream>
#include <iomanip>

#include "polyline/Polyline2D.h"
using namespace crushedpixel;

GLuint program, vao, vbo, vao1, vbo1;
int pointCount = 0;

std::vector<Vec2> points{
		{ -0.25f, -0.5f  },
		{ -0.25f,  0.5f  },
		{  0.25f,  0.25f },
		{  0.0f,   0.0f  },
		{  0.25f, -0.25f },
		{ -0.4f,  -0.25f }
};

bool init()
{
	ShaderInfo si[] = { { GL_VERTEX_SHADER, "Shader.vert" },{ GL_FRAGMENT_SHADER, "Shader.frag" },{ GL_NONE, nullptr } };
	program = LoadShade(si);

	auto thickness = 0.1f;
	auto vertices = Polyline2D::create(points, thickness,
		Polyline2D::JointStyle::MITER,
		Polyline2D::EndCapStyle::SQUARE);
	pointCount = vertices.size();


	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);
	glGenBuffers(1, &vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	glBufferData(GL_ARRAY_BUFFER, vertices.size()*sizeof(vertices[0]), vertices.data(), GL_STATIC_DRAW);
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
	glEnableVertexAttribArray(0);
	glVertexAttrib4f(1, 1.0, 1.0, 1.0, 1.0);


	glGenVertexArrays(1, &vao1);
	glBindVertexArray(vao1);
	glGenBuffers(1, &vbo1);
	glBindBuffer(GL_ARRAY_BUFFER, vbo1);
	glBufferData(GL_ARRAY_BUFFER, points.size()*sizeof(points[0]), points.data(), GL_STATIC_DRAW);
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
	glEnableVertexAttribArray(0);
	glVertexAttrib4f(1, 1.0, 1.0, 1.0, 1.0);

	glClearColor(0.05f, 0.1f, 0.1f, 1.0f);
	return true;
}

void Display(double time)
{
	glClear(GL_COLOR_BUFFER_BIT);

	Matrix4f m;

	glUseProgram(program);
	m = Matrix4f::createScale(1.0f , 1.0f, 1.0f);
	glUniformMatrix4fv(1, 1, GL_FALSE, (float*)m);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);


	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	glUniform4f(2, 0.0f, 1.0f, 1.0f, 0.6f);
	glBindVertexArray(vao);
	glDrawArrays(GL_TRIANGLES, 0, pointCount);

	glLineWidth(1.0f);
	glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
	glUniform4f(2, 0.6f, 0.4f, 0.4f, 1.0f);
	glBindVertexArray(vao);
	glDrawArrays(GL_TRIANGLES, 0, pointCount);

	glUniform4f(2, 0.2f, 0.2f, 0.2f, 0.6f);
	glPointSize(10);
	glBindVertexArray(vao1);
	glDrawArrays(GL_POINTS, 0, points.size());
}

void onClose()
{
	glDeleteVertexArrays(1, &vao);
	glDeleteBuffers(1, &vbo);
}

